<template>
    <div class="row" id="chat">
        <div class="col-sm-offset-1 col-sm-3 conversation-wrap color-wrap">
            <div class="">
                <div class="col-sm-6 fundation-box" :class="navbar == 'friends'? 'select-color':''">
                    <a  class="fundation-box-a" @click="toggle_navbar('friends')">联系人</a>
                </div>
                <div class="col-sm-6 fundation-box" :class="navbar == 'groups'? 'select-color':''">
                    <a class="fundation-box-a" @click="toggle_navbar('groups')">群组</a>
                </div>
                <div class="col-sm-12 fundation-box">
                    <ul class="nav nav-tabs">
                        <li role="presentation" class="dropdown">
                            <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
                                <span class="glyphicon glyphicon-th"></span>
                            </a>
                            <ul class="dropdown-menu">
                                <li v-if="navbar == 'friends'" data-toggle="modal" data-target="#mySelect"><a>添加联系人</a></li>
                                <li v-if="navbar == 'friends'" ><a>删除联系人</a></li>
                                <li v-if="navbar == 'groups'"><a>加入群组</a></li>
                                <li v-if="navbar == 'groups'"><a>删除群组</a></li>
                                <li v-if="navbar == 'groups'"><a>创建群组</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <div id="mySelect" class="modal fade" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <h4>添加联系人</h4>
                            </div>
                            <div class="modal-body">
                                <form class="form-horizontal">
                                    <div class="form-group">
                                        <label for="inputEmail3" class="col-sm-2 control-label">联系人</label>
                                        <div class="col-sm-10">
                                            <input type="email" class="form-control" id="inputEmail3" placeholder="联系人" v-model="linkUser.username">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label for="inputEmail3" class="col-sm-2 control-label">备注信息</label>
                                        <div class="col-sm-10">
                                            <input type="email" class="form-control" id="inputEmail3" placeholder="备注信息" v-model="linkUser.remark">
                                        </div>
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal" @click="addLinkUser">添加</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="navbar == 'friends'" class="mdeia conversation" :class="item.username == selectfriend ? 'bg-primary':'' "  v-for="item in recordList" @click="select(item.username,item.contactcode)" style="clear: both">
                <div class="media-left">
                    <img class="media-object"  style="width: 50px; height: 50px;" src="../img/01.jpg" />
                </div>
                <div class="media-body">
                    <h5 class="media-heading">{{item.username}}</h5>
                    <small>{{item.remark}}</small>
                </div>
            </div>
            <div v-if="navbar == 'groups'" class="mdeia conversation" v-for="item of groups">
                <div class="media-left">
                    <img class="media-object"  style="width: 50px; height: 50px;" src="../img/01.jpg" />
                </div>
                <div class="media-body">
                    <h5 class="media-heading">{{item.groupname}}</h5>
                    <small>{{item.description}}</small>
                </div>
            </div>
        </div>
        <div class="col-sm-7 message-wrap color-wrap">
            <div class="mdeia talk-title" v-if="currentTalker">
                <div class="media-left">
                    <img class="media-object"  style="width: 50px; height: 50px;" src="../img/01.jpg" />
                </div>
                <div class="media-body">
                    <h5 class="media-heading">{{currentTalker}}</h5>
                    <!--<small>我是张三，大家好</small>-->
                </div>
                <button class="btn btn-warning" style="position: absolute;top:5px;right:10px;" @click="close"><span class="glyphicon glyphicon-remove"></span></button>
            </div>
            <div class="msg-wrap" :class="currentTalker ?'talk-msg-wrap':'normal-msg-wrap'" id="myData">
                <div class="media"  v-for="item of showOrigin">
                    <div v-if="item.sender == currentTalker? true:false">
                        <div class="media-left">
                            <img class="media-object"  style="width: 32px; height: 32px;" src="../img/01.jpg" />
                        </div>
                        <div class="media-body">
                            <h5 class="media-heading">{{item.sender}}</h5>
                            <small class="col-sm-10">{{item.data}}</small>
                        </div>
                    </div>
                    <div v-if="item.sender != currentTalker? true:false">
                    <!--<div v-if="false">-->
                        <div class="media-body">
                            <!--<small class="col-sm-offset-2 col-sm-10" style="text-align: right">{{item.sender}}</small>-->
                            <small class="col-sm-offset-2 col-sm-10" style="text-align: right">{{item.data}}</small>
                        </div>
                        <div class="media-right">
                            <img class="media-object"  style="width: 32px; height: 32px;" src="../img/01.jpg" />
                        </div>
                    </div>                   
                </div>
            </div>
            <div class="send-wrap">
                <div>
                    <span class="iconstyle glyphicon glyphicon-font" aria-hidden="true"></span>
                    <!--<router-link :to="audioChat"><span class="iconstyle glyphicon glyphicon-headphones" aria-hidden="true"></span></router-link>-->
                    <a @click="applyAudio"><span class="iconstyle glyphicon glyphicon-headphones" aria-hidden="true"></span></a>
                    <a @click="applyVideo"><span class="iconstyle glyphicon glyphicon-facetime-video" aria-hidden="true"></span></a>
                    <!--<router-link :to="videoChat" :contact="contact" :talker="currentTalker" :media="mediaType"><span class="iconstyle glyphicon glyphicon-facetime-video" aria-hidden="true"></span></router-link>-->
                    <!--<router-link :to="videoChat"><span class="iconstyle glyphicon glyphicon-facetime-video" aria-hidden="true"></span></router-link>-->
                </div>
                <textarea class="form-control send-message" rows="3" style="box-shadow: none" v-model="sendarea" @keyup.enter="send_btn"></textarea>
                <div style="text-align:right">
                    <button class="btn btn-default" @click="send_btn" >发送</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { MessageBox } from 'element-ui';
    import { Message } from 'element-ui'; 
    export default {
        props:['WebRTC','plock'],
        data(){
            return {
                mediaType:'someone',

                groups:null,
                friends:new Map(),
                friendOrigin:[],

                sendarea:null,

                talkUser:null,
                currentRoom:'siQJ8fsv9kBKe99',
                target:'09E39B5299B69E8E6101EEEDCFCD6531',

                selectfriend:null,
                currentTalker:null,
                contactcode:null,
                msgOrigin:new Map(),
                showOrigin:null,
                navbar:'friends',
                linkUser:{
                    username:null,
                    remark:null
                }

                //现在在使用
                // contactList:[]
            }
        },
        watch:{
            contactcode:function(){
                this.showOrigin = this.msgOrigin.get(this.contactcode);
            },
            showOrigin:function(){
                document.getElementById('myData').scrollTop = document.getElementById('myData').scrollHeight;
                // var dataShow = document.getElementById('myData');
                // console.log("scrollTop:"+dataShow.scrollTop);
                // console.log("offsetHeight:"+dataShow.offsetHeight);
                // console.log("scrollHeight:"+dataShow.scrollHeight);
                // dataShow.scrollTop = dataShow.scrollHeight - dataShow.offsetHeight;
            }
            // navbar:function(){
            //     if(this.navbar == 'friends'){
            //         this.recordList = this.friends; 
            //     }else{
            //         this.recordList = this.groups;
            //     }
            // }
        },
        computed:{
            recordList(){
                if(this.navbar == 'groups'){
                    return this.groups;
                }else{
                    return this.friends;
                }
            },
            audioChat(){
                if(this.currentTalker){
                    // return "/AudioChat";
                    return '/AudioChat/'+this.mediaType+'/'+this.contactnode+'/'+this.currentTalker;
                }else{
                    return '';
                }
            },
            videoChat(){
                if(this.currentTalker){
                    // return "/VideoChat";
                    return '/VideoChat/'+this.mediaType+'/'+this.contactnode+'/'+this.currentTalker;
                }else{
                    return '';
                }
            },
            contact(){
                return '1234';
            }
        },
        beforeMount(){
            //判断非游客不能直接登录
            // if(!this.plock){
			// 	// this.$route.push("/");

			// }
            let self = this;
            this.WebRTC.setMsgHandler(this);
            $.ajax({
				type:'POST',
				url:domain+'/mana/recordList',
				dataType:'json',
                xhrFields:{
					withCredentials:true
				},
				success:function(e){
					if("success" == e.code){
                        for(var u of e.data.friends){
                            //创建消息源
                            var origin = [];
                            //绑定通信对象与消息源
                            self.msgOrigin.set(u.contactcode,origin);
                        }
                        self.friends = e.data.friends;
                        self.groups = e.data.groups;
					}else{
						alert("获取联系人失败");
					}
				}
			});
        },
        methods:{
            addLinkUser(){
                let self = this;
                $.ajax({
                    type:'POST',
                    url:domain+'/mana/addfriend',
                    data:self.linkUser,
                    dataType:'json',
                    xhrFields:{
                        withCredentials:true
                    },
                    success:function(e){
                        switch(e.code){
                            case 'success':
                                let self = this;
                                $.ajax({
                                    type:'POST',
                                    url:domain+'/mana/recordList',
                                    dataType:'json',
                                    xhrFields:{
                                        withCredentials:true
                                    },
                                    success:function(e){
                                        if("success" == e.code){
                                            for(var u of e.data.friends){
                                                //创建消息源
                                                var origin = [];
                                                //绑定通信对象与消息源
                                                self.msgOrigin.set(u.contactcode,origin);
                                            }
                                            self.friends = e.data.friends;
                                            self.groups = e.data.groups;
                                        }else{
                                            alert("获取联系人失败");
                                        }
                                    }
                                });
                            break;
                            case 'error-user-null':
                                Message.error("欲添加的联系人不存在");
                            break;
                            case 'error-operation':
                                Message.error("系统操作失败，请重试");
                            break;
                        }
                    }
                });
                this.linkUser = null;
            },
            toggle_navbar(sele){
                this.navbar = sele;
            },
            send_btn(){
                //发送信息
                var text = this.sendarea;
                if(this.currentTalker != null && this.sendarea != null && this.sendarea != '\n'){
                    // this.WebRTC.sendMsg(this.currentTalker,this.sendarea);
                    this.WebRTC.sendTalkMsg(this.currentTalker,text,this.contactcode);
                }
                //发送后，输入区清空
                this.sendarea = null;
            },
            select(event,contact_code){
                console.log(event);
                this.selectfriend = event;
                this.currentTalker = event;
                this.contactcode = contact_code;
            },
            close(){
                this.selectfriend = null;
                this.currentTalker = null;
                this.contactcode = null;
                this.showOrigin = null;
            },
            sendAudioChat(){

            },
            test(){
                console.log("测试呀");
                MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    Message({
                    type: 'success',
                    message: '删除成功!'
                    });
                }).catch(() => {
                    Message({
                    type: 'info',
                    message: '已取消删除'
                    });
                });
            },
            applyAudio(){
                //发送音频申请
                if(this.currentTalker != null){
                    this.WebRTC.sendMsg(this.currentTalker,'audio');
                }
            },
            applyVideo(){
                //发送视频申请
                if(this.currentTalker != null){
                    this.WebRTC.sendMsg(this.currentTalker,'video');
                }
            },
            msghandler(e){
                switch(e.data){
                    case 'cancel':
                        Message.error("对方拒绝通话");
                    break;
                    case 'video':
                        this.receiveVideoApply(e.sender);
                    break;
                    case 'audio':
                        this.receiveAudioApply(e.sender);
                    break;
                    case 'agreeVideo':
                    //跳转页面，发送加入房间指令
                        this.$router.push('/ChatToVideo/wait/'+e.sender);
                    break;
                    case 'agreeAudio':
                    //跳转页面，发送加入房间指令
                        this.WebRTC.sendMsg(e.sender,'joinAudioChat');
                        this.$router.push('/AudioChat');
                    break;
                    case 'joinVideoChat':
                        this.$router.push('/ChatToVideo/join/'+e.sender);
                    break;
                    case 'joinAudioChat':
                        this.$router.push('/AudioChat');
                    break;
                    default:
                        //聊天信息处理
                        console.log(e);
                        if(e.dest != null){
                            let mo = this.msgOrigin.get(e.dest);
                            mo.push(e);
                        }
                    break;
                }
            },
            receiveVideoApply(user){
                let msg = '用户'+user+'请求视频通话';
                MessageBox.confirm(msg+', 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.WebRTC.sendMsg(user,'agreeVideo');
                }).catch(() => {
                    this.WebRTC.sendMsg(user,'cancel');
                });
            },
            receiveAudioApply(user){
                let msg = '用户'+user+'请求音频通话';
                MessageBox.confirm(msg+', 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.WebRTC.sendMsg(user,'agreeAudio');
                }).catch(() => {
                    this.WebRTC.sendMsg(user,'cancel');
                });
            }
        }
    }
</script>

<style scoped>
#chat{
    /*margin-top:50px;*/
    /*padding: 25px 0;*/
    /*background: url("../img/chat_bag04.jpg");*/
    /*padding-top:50px;*/
    height: 100%;
    background: #EAEAEA;
}

.select-color{
    background: #C2C2C2;
}

.fundation-box{
    text-align: center;
    padding-top:10px;
    padding-bottom: 10px;
}

.fundation-box-a{
    cursor: pointer;
    text-decoration: none;
}

.color-wrap{
    background: #fff;
}

.conversation-wrap{
    box-shadow: -2px 0 3px #ddd;
    padding:0;
    padding-right:5px;
    max-height: 551px;
    height: 551px;
    overflow: auto;
    margin-top:50px;
    
    border-radius: 5px;
    margin-right: 3px
}

.conversation{
    padding:5px;
    border-bottom:1px solid #ddd;
    margin:0;
    border-radius: 5px;
}

.message-wrap{
    box-shadow: 0 0 3px #ddd;
    /*box-shadow: 0 0 10px #337ab7;*/
    padding:0;
    margin-top:50px;
    border-radius: 5px;
}

.msg-wrap{
    padding:5px;
    /*border-bottom:1px solid #ddd;*/
    margin:0;
    overflow: auto;
}

.send-wrap{
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    padding:10px;
    /*background: #f8f8f8;*/
}

.send-message{
    resize: none;
    border: 0;
}

.iconstyle{
    font-size: 18px;
    margin:0 5px;
}

.playSelect{
    background:#F5F5F5;
}

.cancelSelect{
    background: red;
}

.talk-title{
    padding:5px;
    border-bottom:1px solid #ddd;
    margin:0;
}

.normal-msg-wrap{
    height:400px;
}

.talk-msg-wrap{
    height: 339px;
}

/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/  
::-webkit-scrollbar  
{  
    width: 10px;  
    height: 16px;  
    background-color: #F5F5F5;  
}  
  
/*定义滚动条轨道 内阴影+圆角*/  
::-webkit-scrollbar-track  
{  
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);  
    border-radius: 10px;  
    background-color: #F5F5F5;  
}  
  
/*定义滑块 内阴影+圆角*/  
::-webkit-scrollbar-thumb  
{  
    border-radius: 10px;  
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);  
    background-color: #555;  
}  
</style>